package com.sinowel.flyway.config;


import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

@Component
@Slf4j
public class FlywayLoad {
    @Resource
    private DB db_temp;

    @Resource
    private FlywayConfig flywayConfig;

    public static FlywayLoad flywayLoad;


    public static DB db;

    public static FlywayConfig fc;
    @PostConstruct
    public void init() {
        db = db_temp;
        fc = flywayConfig;
        flywayLoad = this;
    }

    public static void dbMigrate(){
        Map<String, Map<String, String>> datasource = db.getDatasource();
        log.info("============= Start executing the flyway script ===================");
        datasource.forEach((Key,value)->{
            String keyDatasources = Key;
            log.info("============= start executing {} database ===================" ,keyDatasources);
            Flyway flyway = Flyway.configure()
                    .configuration(fc.getFlyway())
                    .dataSource(value.get("url"),value.get("username"),value.get("password"))
                    .locations(value.get("locations"))
                    .schemas(Key)
                    .load();
            flyway.migrate();
            log.info("============= stop executing {} database ===================", keyDatasources);
            log.info("------------------------------------------------------------------------------");
        });
        log.info("============= flyway script execution ends  ===================");
    }
}